package nc.bs.oa.servlet;

import com.alibaba.fastjson.JSONObject;
import nc.bs.dao.BaseDAO;
import nc.bs.framework.adaptor.IHttpServletAdaptor;
import nc.bs.framework.common.InvocationInfoProxy;
import nc.bs.framework.common.NCLocator;
import nc.bs.framework.server.ISecurityTokenCallback;
import nc.jdbc.framework.processor.ColumnProcessor;
import nc.vo.pub.BusinessException;
import ncc.bs.utils.*;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@SuppressWarnings("restriction")
public class yonyouHOPToOAMessageCountService extends HttpServlet implements IHttpServletAdaptor {
	private static final String logName = "oalog";
	private BaseDAO baseDAO;

	private static final long serialVersionUID = -4808637295385591788L;

	@Override
	public void doAction(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		InputLogger.info(logName,"begin-------->1、第三方系统开始调用HOPG获取待办条数【nc.bs.oa.servlet.yonyouHOPToOAMessageCountService】 ");
		resp.setContentType("application/json;charset=UTF-8");
		resp.setCharacterEncoding("UTF-8");
		req.setCharacterEncoding("UTF-8");
		PrintWriter pw = resp.getWriter();
		try {
			NCLocator.getInstance().lookup(ISecurityTokenCallback.class).token("NCSystem".getBytes(),"pfxx".getBytes());
			String dataSource = GetParamConfigUtil.queryGroupSysParam(GloableConfigParam.NCC_DATASOURCE);
			InvocationInfoProxy.getInstance().setUserDataSource(dataSource);
			InputLogger.info(logName,"--------2、第三方请求NCC调用的方法【yonyouHOPService】数据库模拟登陆完成：数据源="+dataSource );
			String userCode = req.getParameter("jobNumber");
			if(userCode == null || "".equals(userCode)) {
				throw new Exception("员工编号不允许为空，请联系三方|");
			}
			Object o = this.getBaseDAO().executeQuery(this.buildUserQuerySQL(userCode), new ColumnProcessor());
			if(o == null || "".equals(o)) {
				throw new BusinessException("员工编号: 【"+userCode+"】,在用友HOPG系统中不存在对应员工,请确定HOPG中是否存在对应员工!");
			}
			Object count = this.getBaseDAO().executeQuery(this.buildMessageCountSQL(userCode), new ColumnProcessor());
			String returnData = this.returnData("200", count, new String("获取待办条数成功".getBytes(), "UTF-8"));
			pw.write(returnData);
		}catch(Exception e) {
			String s = this.returnData("500", null, e.getMessage());
			// 将JSON字符串转换为字节数组
			// 写入输出流
			pw.write(s);
		}
        InputLogger.info(logName,"end-------->第三方系统获取HOPG待办条数，已完成【nc.bs.oa.servlet.yonyouHOPService】 ");
	}

	/**
	 * 获取请求oa参数
	 * @param userCode 单点登录用户
	 * @param url      NCC单点登录地址
	 * @return
	 * @throws BusinessException
	 */
	protected Map<String,Object> getRequestParam(String userCode, String url) throws BusinessException {
		Map<String, Object> map = new HashMap<>();
		map.put("code", userCode);
		map.put("redirect_uri", url);
		map.put("client_id", GetParamConfigUtil.queryGroupSysParam(GloableConfigParam.OA_CLIENT_ID));
		map.put("client_secret", GetParamConfigUtil.queryGroupSysParam(GloableConfigParam.OA_CLIENT_SECRET));
		return map;
	}

	/**
	 * 响应结果格式
	 * @param code
	 * @param data
	 * @param message
	 * @return
	 * @throws BusinessException
	 */
	protected String returnData(String code, Object data, String message) {
		JSONObject json = new JSONObject();
		json.put("code", code);
		json.put("data", data== null ?  "" : data);
		json.put("message", message);
		return json.toString();
	}
	/**
	 * 构建用户消息有关的SQL
	 * @return
	 * @throws BusinessException
	 */
	protected String buildUserQuerySQL(String user_code) throws BusinessException{
		return "select user_code from sm_user where dr = 0 and user_code = '"+user_code+"' ";
	}

	protected String buildMessageCountSQL(String user_code) throws BusinessException{
		StringBuilder sql = new StringBuilder();
		sql.append("SELECT count(*) \n" );
		sql.append("FROM  \n" );
		sql.append(" sm_msg_approve a \n" );
		sql.append( " INNER JOIN sm_msg_user ON a.pk_message = sm_msg_user.pk_message \n" );
		sql.append(" INNER JOIN sm_user ON a.sender = sm_user.cuserid \n" );
		sql.append(" INNER JOIN ( SELECT * FROM pub_wf_instance WHERE WORKFLOW_TYPE IN ( 2, 4 ) ) i ON i.billid = a.billid LEFT outer \n" );
		sql.append(" JOIN pub_workflownote p ON a.pk_detail = p.pk_checkflow \n" );
		sql.append("WHERE \n" );
		sql.append(" sm_msg_user.isdelete = 'N' \n" );
		sql.append(" AND sm_msg_user.destination = 'inbox' \n" );
		sql.append(" AND sm_msg_user.isread = 'N' \n" );
		sql.append(" and sm_msg_user.pk_user in (select cuserid from sm_user where user_code = '"+user_code+"' ) ");
		sql.append(" AND a.pk_group = '0001A210000000000JB9' \n" );
		sql.append("ORDER BY \n" );
		sql.append(" a.sendtime DESC");
		return sql.toString();
	}
	
	@Override
	protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doAction(req, resp);
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doAction(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doAction(req, resp);
	}

	@Override
	protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doAction(req, resp);
	}

	public BaseDAO getBaseDAO() {
		if(null == baseDAO) {
			baseDAO = new BaseDAO(InvocationInfoProxy.getInstance().getUserDataSource());
		}
		return baseDAO;
	}

}
